package services

import (
	context "context"
	"io"
)

type UserService struct{}

func (*UserService) GetUserScore(ctx context.Context, req *UserScoreRequest) (*UserScoreResponse, error) {
	var score int32 = 100
	users := make([]*UserInfo, 0)
	for _, user := range req.Users {
		user.UserScore = score
		score++
		users = append(users, user)
	}

	return &UserScoreResponse{Users: users}, nil
}

//服务端流模式: 注意返回值只有error了, UserScoreResponse不需要直接返回
//服务端流模式(场景: 客户端操作快, 服务端处理比较慢, 客户端一次性发送, 服务端分批次返回给客户端)
func (*UserService) GetUserScoreByServerStream(req *UserScoreRequest,
	stream UserService_GetUserScoreByServerStreamServer) error {
	var score int32 = 100
	users := make([]*UserInfo, 0)
	for index, user := range req.Users {
		user.UserScore = score
		score++
		users = append(users, user)
		//每隔2条发送一次
		if (index+1)%2 == 0 && index > 0 {
			err := stream.Send(&UserScoreResponse{Users: users})
			if err != nil {
				return err
			}
			//清空切片
			users = (users)[0:0]
		}

	}
	// 发送最后一批(假如最后剩下的结果不足2个)
	if len(users) > 0 {
		err := stream.Send(&UserScoreResponse{Users: users})
		if err != nil {
			return err
		}
	}

	return nil
}

//客户端流模式(场景: 客户端操作慢, 服务端处理比较快, 客户端分批次发送, 服务端一次性返回给客户端)
func (*UserService) GetUserScoreByClientStream(stream UserService_GetUserScoreByClientStreamServer) error {
	users := make([]*UserInfo, 0)
	var score int32 = 100
	for {
		//接收客户端流
		req, err := stream.Recv()
		//接收完
		if err == io.EOF {
			err = stream.SendAndClose(&UserScoreResponse{Users: users})
			return err
		}
		//接收出错了
		if err != nil {
			return err
		}

		//数据处理
		for _, user := range req.Users {
			user.UserScore = score
			users = append(users, user)
			score++
		}
	}
}

//双向流模式(场景: 客户端操作快, 服务端处理比较慢, 客户端分批次发送, 服务端分批次返回给客户端)
func (*UserService) GetUserScoreByTWS(stream UserService_GetUserScoreByTWSServer) error {
	users := make([]*UserInfo, 0)
	var score int32 = 100
	//接收, 处理完成就发送回去
	for {
		req, err := stream.Recv()
		//接收完成
		if err == io.EOF {
			return nil
		}
		//接收出错了
		if err != nil {
			return err
		}

		//数据处理
		for _, user := range req.Users {
			user.UserScore = score
			users = append(users, user)
			score++
		}
		//流方式返回
		stream.Send(&UserScoreResponse{Users: users})
		//清空切片
		users = users[0:0]
	}
}

//接口通过命令会自动生成的方法, 不需要可以不实现, 并从 User_grpc.pb.go 中的 UserService 中删除
func (*UserService) mustEmbedUnimplementedUserServiceServer() {

}
